package com.yunian.common.advice;

import com.yunian.common.annotation.IngoreRespongseAdvice;
import com.yunian.common.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {

        if(methodParameter.getDeclaringClass().isAnnotationPresent(IngoreRespongseAdvice.class)){
            return false;
        }else if(methodParameter.getMethod().isAnnotationPresent(IngoreRespongseAdvice.class)){
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o,
                                  MethodParameter methodParameter,
                                  MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        CommonResponse<Object> commonResponse = new CommonResponse<>(0, "成功");

        if(o==null){
            return commonResponse;
        }else if(o instanceof CommonResponse){
            commonResponse = (CommonResponse<Object>) o;
        }else{
            commonResponse.setData(o);
        }
        return commonResponse;
    }
}
